<template>
	<view class="page-body p50 pt100" :class="[app.setCStyle()]">
		<text class="block fs42 font-w600 mt40">注册帐户</text>
		<u-form :model="model"  ref="uForm" :errorType="errorType" class="mt60">
			<view v-if="phoneNumber">
				<u-form-item :rightIconStyle="{color: '#888', fontSize: '32rpx'}" right-icon="phone" :label-position="labelPosition" label="手机号码" label-width="180">
					<u-input :border="border"  disabled="true" v-model="phoneNumber" type="number"></u-input>
				</u-form-item>
			</view>
			<view v-else>
					<u-form-item :rightIconStyle="{color: '#888', fontSize: '32rpx'}" right-icon="phone" :label-position="labelPosition" label="手机号码" prop="mobile" label-width="180">
						<u-input :border="border" placeholder="请输入手机号" v-model="model.mobile" type="number"></u-input>
					</u-form-item>
					
					<u-form-item :label-position="labelPosition" label="验证码" prop="code" label-width="180">
						<u-input :border="border" placeholder="请输入验证码" v-model="model.code" type="text"></u-input>
						<button slot="right" type="success" size="mini" class="bg-base color-ff" @click="getCode">{{codeTips}}</button>
					</u-form-item>
			</view>
			<u-form-item :rightIconStyle="{color: '#888', fontSize: '32rpx'}"  :label-position="labelPosition"
			 label="昵称" prop="nick_name" label-width="180">
				<u-input :border="border" placeholder="请输入昵称" v-model="model.nick_name" type="text"></u-input>
			</u-form-item>
			<u-form-item :label-position="labelPosition" label="新密码" prop="password" label-width="180">
				<u-input :password-icon="true" :border="border" type="password" v-model="model.password" placeholder="请输入密码"></u-input>
			</u-form-item>
			<u-form-item :label-position="labelPosition" label="确认密码" label-width="180" prop="rePassword">
				<u-input :border="border" type="password" v-model="model.rePassword" placeholder="请确认密码"></u-input>
			</u-form-item>
			<u-form-item v-if="showVerify" :label-position="labelPosition" label="图形验证码" prop="verifyCode" label-width="180">
				<u-input :border="border" placeholder="输入验证码" v-model="model.verifyCode" type="text"></u-input>
				<u-image width="200rpx" height="80rpx" :src="verifyUrl" @click="changeVerifyUrl"></u-image>
			</u-form-item>
			<u-form-item v-if="setting.register_invite_code != 0" :rightIconStyle="{color: '#888', fontSize: '32rpx'}" right-icon="account" :label-position="labelPosition" :label="invite_text[setting.register_invite_code]" prop="invite_code" label-width="180">
				<u-input :border="border" :placeholder="'请输入'+invite_text[setting.register_invite_code]" v-model="model.invite_code" type="text"></u-input>
			</u-form-item>
			
			<view class="fs28 mt30 agreement"  @click="showAgreement">
				<checkbox-group class="checkbox-box">
					<checkbox class="checkbox-item" disabled="true" :checked="model.is_agreement == 1?true:false" color="#FE1685" value="cb" />
				</checkbox-group>
				<view class="agr-content">
					请认真阅读并同意 <text class="agr-text">《 用户注册协议 》</text>
				</view>
				
			</view>
			
			<button size="default" shape="circle" class="fs32 primarybtn mt40" type="warning"  @click="submit">提交</button>
			<u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>
		</u-form>
		<view class="verifymodel">
			
		</view>
		<view class="model" v-if="is_agreement">
			<view class="agreement-box">
				<rich-text :nodes="setting.register_agreement"></rich-text>
				<button size="default" shape="circle" class=" mt40 fs30" :class="shopTime>0?'disabledbtn':'primarybtn'" type="warning" @click="colseAgreement">我已认真阅读并同意《 用户注册协议 》<text v-if="shopTime>0">({{shopTime}}s)</text></button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
			data() {
				let that = this;
				return {
					is_agreement:false,
					setting: uni.getStorageSync('setting'),
					verifyUrl: '',
					showVerify:false,
					invite_text:{
						1:'邀请码',
						2:'邀请会员ID',
						3:'邀请会员手机'
					},
					label_invite_text:'',
					phoneNumber:'',
					model: {
						phone: uni.getStorageSync("loginPhone"),
						mobile:'',
						code: '',
						password: '',
						rePassword:'',
						invite_code:'',
						openid:'',
						iv:'',
						encryptedData:'',
						nick_name:''
					},
					rulesgetCode:{
						mobile: [{
								required: true,
								message: '请输入手机号',
								trigger: ['change', 'blur'],
							},
							{
								validator: (rule, value, callback) => {
									// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
									return this.$u.test.mobile(value);
								},
								message: '手机号码不正确',
								// 触发器可以同时用blur和change，二者之间用英文逗号隔开
								trigger: ['change', 'blur'],
							}
						]
					},
					rules: {
						mobile: [
							{
								required: true,
								message: '请输入手机号',
								trigger: ['change','blur'],
							},
							{
								validator: (rule, value, callback) => {
									// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
									return this.$u.test.mobile(value);
								},
								message: '手机号码不正确',
								// 触发器可以同时用blur和change，二者之间用英文逗号隔开
								trigger: ['change','blur'],
							}
						],
						code: [
							{
								min: 6,
								required: true,
								message: '请输入6位验证码',
								trigger: ['change','blur'],
							},
							{
								type: 'number',
								message: '验证码只能为数字',
								trigger: ['change','blur'],
							}
						],
						nick_name:[
							{
								required:  true,
								message: '请输入昵称',
								trigger: ['change','blur'],
							},
						],
						password: [
							{
								required:  true,
								message: '请输入密码',
								trigger: ['change','blur'],
							},
							{
								min: 8,
								message: '密码不能少于8个字符',
								trigger: 'change' ,
							}
						],
						rePassword: [
							{
								required: true,
								message: '请重新输入密码',
								trigger: ['change','blur'],
							},
							{
								validator: (rule, value, callback) => {
									return value === this.model.password;
								},
								message: '两次输入的密码不相等',
								trigger: ['change','blur'],
							}
						],
					},
					border: false,
					check: false,
					labelPosition: 'left',
					codeTips: '',
					errorType: ['toast'],
					shopTime:8,
				};
			},
			onLoad(options) {
				if (options.scene){//获取小程序的场景值，用于获取分享者的token
					let scene = options.scene.split('_');
					uni.setStorageSync("share_token",scene[0]);
				}
				this.app.getWxOauthOpenId(this,options);//默认只有初次打开时触发获取openid,退出登陆后后清理openid后，再访问登陆页重新获取
				if (options.phoneNumber){
					this.phoneNumber = options.phoneNumber;
					let wxEncryptedData = uni.getStorageSync("wxEncryptedData");
					this.model.encryptedData = wxEncryptedData.encryptedData;
					this.model.iv = wxEncryptedData.iv;
					delete this.rules.mobile;
					delete this.rules.code;
				}
				let that = this;
				setTimeout(() => {
					this.$u.get('member/api.passport/getUserid',{share_token:uni.getStorageSync("share_token")}).then(res => {
						that.model.invite_code = res.data.user_id;
					})
					// that.model.invite_code = uni.getStorageSync("share_token");
				},1500);
				this.verifyUrl = this.config.baseUrl + '/index.php/publics/api.index/verify/session_id/'+uni.getStorageSync("session_id");
			},
			computed: {
				borderCurrent() {
					return this.border ? 0 : 1;
				},
			},
			onReady() {
				
			},
			methods: {
				showAgreement(){
					var _this = this
					var settime = setInterval(function(){
						_this.shopTime --; 
						if (_this.shopTime == 0){
							clearInterval(settime);
							return false;
						}
						settime
					},1000)
					_this.is_agreement = true;
				},
				colseAgreement(){
					if (this.shopTime > 0) {
						this.$u.toast('请先仔细阅读注册协议.');
						return false;
					}
					this.is_agreement = false;
					this.model.is_agreement = 1;
				},
				submit() {
					this.model.openid = this.app.getWxOpenId();
					this.model.platform = this.app.getPlatform();
					this.$refs.uForm.setRules(this.rules);
					this.$refs.uForm.validate(valid => {
						if (!valid) {
							return false;
						}
						//验证手机验证码
						this.$u.get('member/api.passport/register',this.model).then(res => {
							if (res.code < 0){
								this.showVerify = res.data.showVerify;
								this.$u.toast(res.msg);
								this.changeVerifyUrl();
								this.model.verifyCode = '';
								return false;
							}
							uni.showModal({
							    title: '提示',
							    content: '注册成功，前往登录.',
								showCancel:false,
							    success: function (res) {
							        if (res.confirm) {
							           uni.navigateTo({
							           	url: '/pages/member/passport/login'
							           });
							        } 
							    }
							});
							
						})
						
					});
				},
				codeChange(text) {
					this.codeTips = text;
				},
				changeVerifyUrl() {
					if (this.verifyUrl.indexOf('rand=') > -1) {
						this.verifyUrl = this.verifyUrl.substr(0, this.verifyUrl.length - 19);
					}
					this.verifyUrl += '?rand=' + new Date().getTime();
				},
				// 获取验证码
				getCode() {
					let _this = this;
					if(_this.$refs.uCode.canGetCode) {
						_this.$refs.uForm.setRules(_this.rulesgetCode);
						_this.$refs.uForm.validate(valid => {
							if (valid) {
								// 向后端请求验证码
								uni.showLoading({
									title: '正在获取验证码',
									mask: true
								})
								_this.$u.get('publics/api.sms/sendCode', {
									'type': 'register',
									'mobile': _this.model.mobile
								}).then(res => {
									uni.hideLoading();
									// 这里此提示会被_this.start()方法中的提示覆盖
									if (res.data.code){
										let that = this;
										let contentText = '测试状态，验证码为'+res.data.code;
										let code = res.data.code;
										uni.showModal({
											title: '提示',
											content: contentText,
											showCancel: false,
											confirmText:'复制',
											success: function(res) {
												that.app.copy(code);
											}
										});
										// this.$u.toast('测试状态，验证码自动填充');
										// this.model.code = res.data.code;
									}else{
										_this.$u.toast('验证码已发送');
									}
									_this.user_exist = res.data.user_exist;
									// 通知验证码组件内部开始倒计时
									_this.$refs.uCode.start();
								})
							}
						});
					} else {
						_this.$u.toast('倒计时结束后再发送');
					}
				},
			}
		}
</script>
<style lang="scss">
	.agreement{
		display: flex;
		justify-content: flex-start;
		.checkbox-box{
			display: inline-block;
			vertical-align: middle;
			transform:scale(0.8);
			color: #FE1685;
			border-color: #FE1685;
			.checkbox-item{
				color: #FE1685;
				// transform:scale(0.8);
			}
		}
		.agr-content{
			display: inline-block;
			vertical-align: middle;
			margin-top: 5rpx;
			.agr-text {
				color: #0000cc;
			}
		}
	}
	.agreement-box{
		width: 96%;
		height: 98%;
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%,-50%);
		background-color: #fff;
		padding: 30rpx;
		overflow: auto;
	}
	.disabledbtn{
		color: #999;
		cursor:no-drop
	}
	
</style>
